
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text("File Network Widget Demo"),
      ),
      body: WebSocketWidget(),
    ),
  ));
}

class WebSocketWidget extends StatefulWidget {
  const WebSocketWidget({Key? key}) : super(key:key);

  @override
  _WebSocketWidgetState createState() => _WebSocketWidgetState();
}

class _WebSocketWidgetState extends State<WebSocketWidget> {
  TextEditingController _controller = TextEditingController();
  late IOWebSocketChannel channel;
  String _text = "";

  @override
  void initState() {
    // 创建websocket连接
    channel = IOWebSocketChannel.connect(Uri.parse('ws://82.157.123.54:9010/ajaxchattest'));
  }


  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Form(
            child: TextFormField(
              controller: _controller,
              decoration: const InputDecoration(labelText: 'send a message'),
            ),
          ),
          StreamBuilder(
            stream: channel.stream,
            builder: (context, snapshot){
              // 网路不通不会走到这
              if (snapshot.hasError) {
                _text = "网络不通";
              } else if (snapshot.hasData) {
                _text = "echo: ${snapshot.data}";
              }
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 24.0),
                child: Text(_text),
              );
            },
          ),
          ElevatedButton(
            onPressed: _sendMessage,
            child: Row(
              children: const [
                Icon(Icons.send),
                Text('send message'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      channel.sink.add(_controller.text);
    }
  }

  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }
}